<?php

namespace app\admin\controller;

use think\Controller;

/*
*   $res = new MakeZip($dir,$zipName);
*@ $dir是被压缩的文件夹名称,可使用路径，例 'a'或者'a/test.txt'或者'test.txt'
*@ $zipName是压缩后的压缩包名称，可使用路径，例 'a/test.zip'或者'test.zip'
**/
class Makezip extends Controller
{
    private $_dir;
    private $_zipDir;
    private $_zipName;
    
    public function __construct($dir,$zipName) {
        $this->_dir = $dir;
        $this->_zipDir = basename($dir);
        $this->_zipName = $zipName;
        $this->mkdirs();
        $this->creat();
    }
    //检测并生成目录
    private function mkdirs() {
        if (!is_dir(dirname($this->_zipName))) {
            $arr = explode('/', dirname($this->_zipName));
            $arrs = '';
            foreach($arr as $value) {
                if (!is_dir($arrs.$value)) {
                    if (!!mkdir($arrs.$value)) {
                        $arrs .= $value.'/';
                    }
                }
            }
        }
    }
    //生成Zip压缩包
    private function creat() {
        $zip = new \ZipArchive;
        if (is_dir($this->_dir)) {
            $this->readDir($this->_dir,$files);
            if ($zip->open($this->_zipName,\ZipArchive::CREATE)) {
                foreach ($files as $value) {
                    preg_match('/\/('.$this->_zipDir.'\/.*)/', $value, $match);
                    if (is_dir($value)) {
                        @$zip->addEmptyDir($value, $match[1]);
                    } else {
                        @$zip->addFile($value, $match[1]);
                    }
                }
                $zip->close();
            }
        } else {
            if ($zip->open($this->_zipName,\ZipArchive::CREATE)) {
                $zip->addFile($this->_dir, basename($this->_dir));
            }
        }
    }
    //读取文件夹所有文件
    private function readDir($dir,&$arr) {
        if ($dirs = opendir($dir)) {
            while (($file=readdir($dirs)) != false) {
                if ($file == '.' || $file == '..') continue;
                $files = $dir .'/'. $file;
                if (is_dir($files) && $this->isEmpty($files)) {
                    $this->readDir($files,$arr);
                } else {
                    $arr[] = $files;
                }
            }
        }
        closedir($dirs);
    }
    //判断文件夹是否为空
    private function isEmpty($dir) {
        if ($dirs = opendir($dir)) {
            while (($file=readdir($dirs)) != false) {
                if($file != '.' && $file != '..') {
                    closedir($dirs);
                    return true;
                    break;
                }
            }
            closedir($dirs);
            return false;
        }
    }
}